<template>
  <div class="feedback-management">
    <el-container>
      <el-header class="feedback-header">
        <div class="header-content">
          <h2>反馈处理管理</h2>
          <div class="header-actions">
            <el-button @click="refreshData">刷新数据</el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </el-header>
      
      <el-main class="feedback-main">
        <!-- 当前管理员信息 -->
        <el-card class="admin-info-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>当前管理员</span>
            </div>
          </template>
          
          <div class="current-admin-info">
            <el-tag type="primary" size="large">
              <el-icon><User /></el-icon>
              {{ selectedAdminName || '加载中...' }}
            </el-tag>
          </div>
        </el-card>

        <!-- 反馈处理区域 -->
        <el-card 
          v-if="selectedAdminId" 
          class="feedback-area" 
          shadow="never"
        >
          <template #header>
            <div class="card-header">
              <div class="admin-info">
                <h3>{{ selectedAdminName }} - 反馈处理</h3>
              </div>
              <div class="tab-actions">
                <el-button @click="loadPendingFeedbacks">刷新待处理</el-button>
                <el-button @click="loadProcessedFeedbacks">刷新已处理</el-button>
              </div>
            </div>
          </template>

          <!-- 标签页 -->
          <el-tabs v-model="activeTab" @tab-change="onTabChange">
            <!-- 待处理反馈 -->
            <el-tab-pane label="待处理反馈" name="pending">
              <el-table
                :data="pendingFeedbacks"
                v-loading="pendingLoading"
                border
                style="width: 100%"
              >
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="id" label="反馈ID" width="80" />
                <el-table-column prop="doctorName" label="医生姓名" width="120" />
                <el-table-column prop="content" label="反馈内容" min-width="200" show-overflow-tooltip />
                <el-table-column prop="createTime" label="提交时间" width="160">
                  <template #default="{ row }">
                    {{ formatDateTime(row.createTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="{ row }">
                    <el-tag 
                      :type="getStatusType(row.status)"
                      size="small"
                    >
                      {{ getStatusText(row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                  <template #default="{ row }">
                    <el-button 
                      type="primary" 
                      size="small" 
                      @click="showProcessDialog(row)"
                    >
                      处理
                    </el-button>
                    <el-button 
                      type="info" 
                      size="small" 
                      @click="showDetailDialog(row)"
                    >
                      详情
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>

            <!-- 已处理反馈 -->
            <el-tab-pane label="已处理反馈" name="processed">
              <el-table
                :data="processedFeedbacks"
                v-loading="processedLoading"
                border
                style="width: 100%"
              >
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="id" label="反馈ID" width="80" />
                <el-table-column prop="doctorName" label="医生姓名" width="120" />
                <el-table-column prop="content" label="反馈内容" min-width="200" show-overflow-tooltip />
                <el-table-column prop="createTime" label="提交时间" width="160">
                  <template #default="{ row }">
                    {{ formatDateTime(row.createTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="{ row }">
                    <el-tag 
                      :type="getStatusType(row.status)"
                      size="small"
                    >
                      {{ getStatusText(row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="adminReply" label="管理员回复" min-width="150" show-overflow-tooltip />
                <el-table-column prop="updateTime" label="处理时间" width="160">
                  <template #default="{ row }">
                    {{ formatDateTime(row.updateTime) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120" fixed="right">
                  <template #default="{ row }">
                    <el-button 
                      type="info" 
                      size="small" 
                      @click="showDetailDialog(row)"
                    >
                      详情
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-main>
    </el-container>

    <!-- 处理反馈对话框 -->
    <el-dialog
      v-model="processDialogVisible"
      title="处理反馈"
      width="600px"
    >
      <div class="process-content">
        <div class="feedback-info">
          <h4>反馈信息</h4>
          <p><strong>反馈ID：</strong>{{ selectedFeedback?.id }}</p>
          <p><strong>医生姓名：</strong>{{ selectedFeedback?.doctorName }}</p>
          <p><strong>反馈内容：</strong></p>
          <div class="feedback-content">{{ selectedFeedback?.content }}</div>
          <p><strong>提交时间：</strong>{{ formatDateTime(selectedFeedback?.createTime) }}</p>
        </div>

        <el-form
          ref="processFormRef"
          :model="processForm"
          :rules="processRules"
          label-width="100px"
        >
          <el-form-item label="处理状态" prop="status">
            <el-select v-model="processForm.status" placeholder="请选择处理状态">
              <el-option label="处理中" value="PROCESSING" />
              <el-option label="已解决" value="RESOLVED" />
              <el-option label="已拒绝" value="REJECTED" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="管理员回复" prop="adminReply">
            <el-input
              v-model="processForm.adminReply"
              type="textarea"
              :rows="4"
              placeholder="请输入回复内容"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmProcess"
            :loading="processLoading"
          >
            确认处理
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 反馈详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="反馈详情"
      width="600px"
    >
      <div class="detail-content" v-if="selectedFeedback">
        <div class="detail-section">
          <h4>基本信息</h4>
          <p><strong>反馈ID：</strong>{{ selectedFeedback.id }}</p>
          <p><strong>医生姓名：</strong>{{ selectedFeedback.doctorName }}</p>
          <p><strong>医生ID：</strong>{{ selectedFeedback.doctorId }}</p>
          <p><strong>提交时间：</strong>{{ formatDateTime(selectedFeedback.createTime) }}</p>
          <p><strong>当前状态：</strong>
            <el-tag :type="getStatusType(selectedFeedback.status)" size="small">
              {{ getStatusText(selectedFeedback.status) }}
            </el-tag>
          </p>
        </div>
        
        <div class="detail-section">
          <h4>反馈内容</h4>
          <div class="feedback-content">{{ selectedFeedback.content }}</div>
        </div>
        
        <div class="detail-section" v-if="selectedFeedback.adminReply">
          <h4>管理员回复</h4>
          <div class="admin-reply">{{ selectedFeedback.adminReply }}</div>
          <p><strong>处理时间：</strong>{{ formatDateTime(selectedFeedback.updateTime) }}</p>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User } from '@element-plus/icons-vue'
import { 
  getAdminNames,
  getProcessedFeedbacksByAdmin,
  getPendingFeedbacksByAdmin,
  updateFeedbackStatus
} from '@/api/feedback'

export default {
  name: 'FeedbackManagement',
  setup() {
    const router = useRouter()
    
    // 管理员列表
    const adminList = ref([])
    const selectedAdminId = ref(null)
    const currentAdminInfo = ref(null)
    
    // 反馈数据
    const pendingFeedbacks = ref([])
    const processedFeedbacks = ref([])
    const pendingLoading = ref(false)
    const processedLoading = ref(false)
    
    // 当前标签页
    const activeTab = ref('pending')
    
    // 对话框状态
    const processDialogVisible = ref(false)
    const detailDialogVisible = ref(false)
    const processLoading = ref(false)
    const selectedFeedback = ref(null)
    const processFormRef = ref(null)
    
    // 处理表单
    const processForm = reactive({
      status: '',
      adminReply: ''
    })
    
    // 表单验证规则
    const processRules = {
      status: [
        { required: true, message: '请选择处理状态', trigger: 'change' }
      ],
      adminReply: [
        { required: true, message: '请输入回复内容', trigger: 'blur' },
        { min: 5, message: '回复内容至少5个字符', trigger: 'blur' }
      ]
    }
    
    // 计算属性
    const selectedAdminName = computed(() => {
      return currentAdminInfo.value ? currentAdminInfo.value.realName : ''
    })
    
    // 初始化当前管理员信息
    const initCurrentAdmin = () => {
      try {
        const adminInfo = JSON.parse(localStorage.getItem('adminInfo') || '{}')
        if (adminInfo.id) {
          currentAdminInfo.value = adminInfo
          selectedAdminId.value = adminInfo.id
          // 自动加载反馈数据
          if (activeTab.value === 'pending') {
            loadPendingFeedbacks()
          } else {
            loadProcessedFeedbacks()
          }
        } else {
          ElMessage.error('未找到管理员信息，请重新登录')
          router.push('/admin-login')
        }
      } catch (error) {
        console.error('初始化管理员信息失败:', error)
        ElMessage.error('初始化管理员信息失败')
        router.push('/admin-login')
      }
    }
    
    // 加载管理员列表（保留用于其他功能）
    const loadAdminList = async () => {
      try {
        const response = await getAdminNames()
        if (response.code === 200) {
          adminList.value = response.data
        } else {
          ElMessage.error(response.message || '获取管理员列表失败')
        }
      } catch (error) {
        console.error('获取管理员列表失败:', error)
        ElMessage.error('获取管理员列表失败')
      }
    }
    
    // 加载待处理反馈
    const loadPendingFeedbacks = async () => {
      if (!selectedAdminId.value) return
      
      pendingLoading.value = true
      try {
        const response = await getPendingFeedbacksByAdmin(selectedAdminId.value)
        if (response.code === 200) {
          pendingFeedbacks.value = response.data
        } else {
          ElMessage.error(response.message || '获取待处理反馈失败')
        }
      } catch (error) {
        console.error('获取待处理反馈失败:', error)
        ElMessage.error('获取待处理反馈失败')
      } finally {
        pendingLoading.value = false
      }
    }
    
    // 加载已处理反馈
    const loadProcessedFeedbacks = async () => {
      if (!selectedAdminId.value) return
      
      processedLoading.value = true
      try {
        const response = await getProcessedFeedbacksByAdmin(selectedAdminId.value)
        if (response.code === 200) {
          processedFeedbacks.value = response.data
        } else {
          ElMessage.error(response.message || '获取已处理反馈失败')
        }
      } catch (error) {
        console.error('获取已处理反馈失败:', error)
        ElMessage.error('获取已处理反馈失败')
      } finally {
        processedLoading.value = false
      }
    }
    
    // 管理员选择变化（已移除，现在使用当前登录的管理员）
    
    // 标签页变化
    const onTabChange = (tabName) => {
      if (selectedAdminId.value) {
        if (tabName === 'pending') {
          loadPendingFeedbacks()
        } else {
          loadProcessedFeedbacks()
        }
      }
    }
    
    // 显示处理对话框
    const showProcessDialog = (feedback) => {
      selectedFeedback.value = feedback
      processForm.status = feedback.status === 'PENDING' ? 'PROCESSING' : feedback.status
      processForm.adminReply = ''
      processDialogVisible.value = true
    }
    
    // 显示详情对话框
    const showDetailDialog = (feedback) => {
      selectedFeedback.value = feedback
      detailDialogVisible.value = true
    }
    
    // 确认处理
    const confirmProcess = async () => {
      if (!processFormRef.value) return
      
      try {
        await processFormRef.value.validate()
        
        processLoading.value = true
        
        const response = await updateFeedbackStatus(selectedFeedback.value.id, {
          status: processForm.status,
          adminReply: processForm.adminReply
        })
        
        if (response.code === 200) {
          ElMessage.success('处理成功')
          processDialogVisible.value = false
          
          // 刷新当前标签页的数据
          if (activeTab.value === 'pending') {
            loadPendingFeedbacks()
          } else {
            loadProcessedFeedbacks()
          }
        } else {
          ElMessage.error(response.message || '处理失败')
        }
      } catch (error) {
        console.error('处理反馈失败:', error)
        ElMessage.error('处理反馈失败')
      } finally {
        processLoading.value = false
      }
    }
    
    // 获取状态类型
    const getStatusType = (status) => {
      const statusMap = {
        'PENDING': 'warning',
        'PROCESSING': 'primary',
        'RESOLVED': 'success',
        'REJECTED': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'PENDING': '待处理',
        'PROCESSING': '处理中',
        'RESOLVED': '已解决',
        'REJECTED': '已拒绝'
      }
      return statusMap[status] || status
    }
    
    // 格式化时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString('zh-CN')
    }
    
    // 刷新数据
    const refreshData = () => {
      loadAdminList()
      if (selectedAdminId.value) {
        if (activeTab.value === 'pending') {
          loadPendingFeedbacks()
        } else {
          loadProcessedFeedbacks()
        }
      }
    }
    
    // 返回
    const goBack = () => {
      router.go(-1)
    }
    
    onMounted(() => {
      initCurrentAdmin()
    })
    
    return {
      adminList,
      selectedAdminId,
      selectedAdminName,
      pendingFeedbacks,
      processedFeedbacks,
      pendingLoading,
      processedLoading,
      activeTab,
      processDialogVisible,
      detailDialogVisible,
      processLoading,
      selectedFeedback,
      processFormRef,
      processForm,
      processRules,
      onTabChange,
      showProcessDialog,
      showDetailDialog,
      confirmProcess,
      getStatusType,
      getStatusText,
      formatDateTime,
      refreshData,
      goBack
    }
  }
}
</script>

<style scoped>
.feedback-management {
  height: 100vh;
  background-color: #f5f5f5;
}

.feedback-header {
  background: white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  padding: 0;
}

.header-content {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.feedback-main {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.admin-info-card {
  background: white;
}

.current-admin-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.current-admin-info .el-tag {
  font-size: 16px;
  padding: 12px 16px;
  border-radius: 8px;
}

.feedback-area {
  background: white;
  flex: 1;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.admin-info h3 {
  margin: 0;
  color: #303133;
}

.tab-actions {
  display: flex;
  gap: 10px;
}

.process-content {
  padding: 0;
}

.feedback-info {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.feedback-info h4 {
  margin: 0 0 10px 0;
  color: #409eff;
  font-size: 16px;
}

.feedback-info p {
  margin: 5px 0;
  color: #606266;
}

.feedback-content {
  background: white;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  margin: 10px 0;
  white-space: pre-wrap;
  word-break: break-word;
}

.detail-content {
  padding: 0;
}

.detail-section {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.detail-section:last-child {
  margin-bottom: 0;
}

.detail-section h4 {
  margin: 0 0 10px 0;
  color: #409eff;
  font-size: 16px;
}

.detail-section p {
  margin: 5px 0;
  color: #606266;
}

.admin-reply {
  background: white;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  margin: 10px 0;
  white-space: pre-wrap;
  word-break: break-word;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table .cell) {
  padding: 8px 0;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 500;
}

:deep(.el-table--border) {
  border: 1px solid #ebeef5;
}

:deep(.el-table--border::after) {
  background-color: #ebeef5;
}

:deep(.el-table td) {
  border-bottom: 1px solid #ebeef5;
}
</style>
